package cn.itrip.trade.service.impl;

import cn.itrip.beans.pojo.ItripHotelOrder;
import cn.itrip.common.AliPayUtil;
import cn.itrip.common.AlipayConfig;
import cn.itrip.dao.PayMapper;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author:小伟
 * @Description:
 * @Date:2020-03-18 16:33
 **/
@Service
public class AliPayService {
    @Resource
    private PayMapper mapper;
    Logger logger = LoggerFactory.getLogger("AliPayService.class");

    /**
     * 根据订单号查询订单
     *
     * @param orderNo
     * @return
     */
    public Object aliPay(String orderNo) {
        try {
            if (orderNo != null && !"".equals(orderNo)) {
                ItripHotelOrder order = mapper.getOrderNo(orderNo);
                //获得初始化的AlipayClient
                AlipayClient alipayClient = AliPayUtil.alipayClient;
                // 订单模型
                String productCode = "FAST_INSTANT_TRADE_PAY";
                AlipayTradePagePayModel model = new AlipayTradePagePayModel();
                //商户订单号,64个字符以内、可包含字母、数字、下划线；需保证在商户端不重复
                model.setOutTradeNo(order.getOrderNo());
                //订单标题
                model.setSubject(order.getHotelName());
                //订单价格
                model.setTotalAmount(order.getPayAmount().toString());
                model.setProductCode(productCode);
                model.setTimeoutExpress("1h");

                AlipayTradePagePayRequest pagePayRequest = new AlipayTradePagePayRequest();
                pagePayRequest.setReturnUrl(AlipayConfig.return_url);
                pagePayRequest.setNotifyUrl(AlipayConfig.notify_url);
                pagePayRequest.setBizModel(model);
                //请求
                String result = alipayClient.pageExecute(pagePayRequest).getBody();
                logger.info(result);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "支付失败!";
    }
}